package mirrormonkey.framework.test.application;

import mirrormonkey.commons.graph.MakeVisibleListener;
import mirrormonkey.core.client.ClientCoreModule;
import mirrormonkey.core.client.ClientEntityData;
import mirrormonkey.framework.ClientSyncAppState;
import mirrormonkey.framework.entity.SyncEntity;

import com.jme3.network.Client;
import com.jme3.network.Network;
import com.jme3.system.AppSettings;
import com.jme3.system.JmeContext;

public class ClientTestApplication extends TestApplication<ClientSyncAppState> {

	public final Client client;

	public final MakeVisibleListener vListener;

	public final ClientCoreModule coreModule;

	public ClientTestApplication() throws Throwable {
		this(Network.connectToServer("localhost", PORT));
	}

	public ClientTestApplication(Client client) throws Throwable {
		super(new ClientSyncAppState(client));
		this.client = client;

		setShowSettings(false);
		settings = new AppSettings(true);
		settings.setUseInput(false);

		vListener = new MakeVisibleListener(this);

		coreModule = appState.getModule(ClientCoreModule.class);
		coreModule.getListenerConfiguration().addListener(generalListener);
		coreModule.getListenerConfiguration().addListener(vListener);
	}

	public ClientEntityData getClientData(SyncEntity entity) {
		return coreModule.getData(entity.getData().getId());
	}

	@Override
	public void start() {
		start(JmeContext.Type.Display);
	}

	@Override
	public void start(JmeContext.Type type) {
		client.start();
		super.start(type);
	}

	@Override
	public void stop() {
		if (client.isConnected()) {
			client.close();
		}
		super.stop(true);
		// try {
		destroy();
		// } catch (IllegalStateException e) {}
	}

	@Override
	public void clear() {
		while (coreModule.getEntityProvider().hasEntities()) {
			ClientEntityData d = (ClientEntityData) coreModule
					.getEntityProvider().getEntities().iterator().next();
			coreModule.getEntityProvider().removeData(d);
			d.setStaticData(null);
			if (d.isEntityPresent()) {
				d.getEntity().setData(null);
				d.referenceDeparted();
			}
		}
		super.clear();
		getRootNode().detachAllChildren();
	}
}